package com.lzj.jiangxindaojia.view.login;

import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ifaa.sdk.auth.Constants;
import com.lzj.jiangxindaojia.MainActivity;
import com.lzj.jiangxindaojia.R;
import com.lzj.jiangxindaojia.base.BaseActivity;
import com.lzj.jiangxindaojia.bean.Login;
import com.lzj.jiangxindaojia.bean.ResultCode;
import com.lzj.jiangxindaojia.bean.SdkLogin;
import com.lzj.jiangxindaojia.http.HttpAction;
import com.lzj.jiangxindaojia.http.HttpCallBack;
import com.lzj.jiangxindaojia.http.HttpConstans;
import com.lzj.jiangxindaojia.http.HttpUtil;
import com.lzj.jiangxindaojia.utils.GsonUtil;
import com.lzj.jiangxindaojia.utils.LogUtils;
import com.lzj.jiangxindaojia.utils.MD5;
import com.lzj.jiangxindaojia.utils.SharePreferenceUtil;
import com.lzj.jiangxindaojia.utils.Utils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizj on 2017/12/5.
 */

public class PwdLoginActivity extends BaseActivity implements HttpCallBack {

    private TextView tv_tile;
    private ImageView iv_left,tv_getyanzhnengma;
    private LinearLayout ll_left;
    private TextView login_forgetpwd,login_zhiwen;
    private Button btn_login,btn_regist;
    private EditText login_phone,login_pwd;
    private RelativeLayout rl_wb,rl_wx,rl_qq;
    private UMShareAPI mShareAPI;
    private HttpCallBack callBack;
    @Override
    protected void initData() {
        super.initData();
        this.tv_tile = ((TextView)findViewById(R.id.tv_tile));
        this.iv_left = ((ImageView)findViewById(R.id.iv_left));
        this.ll_left = ((LinearLayout)findViewById(R.id.ll_left));
        this.tv_tile.setText(R.string.login_title);
        iv_left.setImageResource(R.mipmap.back);
        this.ll_left.setVisibility(View.GONE);
        btn_regist = ((Button)findViewById(R.id.btn_regist));
        login_forgetpwd = ((TextView)findViewById(R.id.login_forgetpwd));
        login_zhiwen = ((TextView)findViewById(R.id.login_zhiwen));
        btn_login = ((Button)findViewById(R.id.btn_login));
        login_phone = ((EditText)findViewById(R.id.login_phone));
        login_pwd = ((EditText)findViewById(R.id.login_pwd));
        this.tv_getyanzhnengma = ((ImageView)findViewById(R.id.tv_getyanzhnengma));

        rl_wx = ((RelativeLayout)findViewById(R.id.rl_wx));
        rl_wb = ((RelativeLayout)findViewById(R.id.rl_wb));
        rl_qq = ((RelativeLayout)findViewById(R.id.rl_qq));
        this.mShareAPI = UMShareAPI.get(this);
        callBack = this;

    }

    /**
     * 检测是否支持IFAA
     */
    private int authType = Constants.TYPE_FINGERPRINT;
    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void requestServer() {
        super.requestServer();
    }


    Login login;
    SdkLogin sdkLogin;
    @Override
    public <T> void onSuccess(String  result, String action) {
        switch (action){
            case HttpAction.LOGIN:
                login = GsonUtil.GsonToBean(result, Login.class);
                if(ResultCode.SUCCESS.equals(login.getStatus())){
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.USER_ID,login.getData().getUser_id());
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.TOKEN,login.getData().getToken());
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_INFO,login.getData().getOpen_info());
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_USERID,login.getData().getOpen_userid());
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_ID,login.getData().getOpenid());
                    if("".equals(login.getData().getLogin_token())||login.getData().getLogin_token()==null){

                    }else{
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.REGIST_LOGINTOKEN,login.getData().getLogin_token());
                    }

                    Utils.goNextActivity(this,MainActivity.class);
                }else{
                    Utils.showToast(this,login.getMsg());
                }
                break;
            case HttpAction.SDK_LOGIN:
                sdkLogin = GsonUtil.GsonToBean(result, SdkLogin.class);
                if(ResultCode.SUCCESS.equals(sdkLogin.getStatus())){
                    Utils.goNextActivity(this,BindPhoneActivity.class);
                    SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_INFO,sdkLogin.getData().getOpen_info());
                }else{
                    if(sdkLogin.getData()==null){
                        Utils.showToast(this,sdkLogin.getMsg());
                    }else{
                        //保存跳转首页信息
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.USER_ID,sdkLogin.getData().getUserId());
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.TOKEN,sdkLogin.getData().getToken());
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_INFO,sdkLogin.getData().getOpen_info());
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_USERID,sdkLogin.getData().getOpen_userid());
                        SharePreferenceUtil.keepDate(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.OPEN_ID,uid);
                        Utils.goNextActivity(this,MainActivity.class);
                    }


                }
                break;
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        btn_regist.setOnClickListener(this);
        login_forgetpwd.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        login_zhiwen.setOnClickListener(this);
        tv_getyanzhnengma.setOnClickListener(this);
        rl_wx.setOnClickListener(this);
        rl_wb.setOnClickListener(this);
        rl_qq.setOnClickListener(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_pwdlogin;
    }


    private String  tel,pwd;
    private HashMap paramMap;
    private boolean pwdflag = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_regist:
                Utils.goNextActivity(this,RegistActivity.class);
                break;
            case R.id.login_forgetpwd:
                Utils.goNextActivity(this,ResetpwdActivity.class);

                break;
            case R.id.btn_login:
                this.tel = this.login_phone.getText().toString().trim();
                this.pwd = this.login_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(this.tel)) {
                    Utils.showToast(this, getResources().getString(R.string.please_input_uname));
                    return;
                }
                if (TextUtils.isEmpty(this.pwd)) {
                    Utils.showToast(this, getResources().getString(R.string.please_input_pwd));
                    return;
                }

                paramMap = new HashMap();
                paramMap.put("channel_number", HttpConstans.qdnumber);
                paramMap.put("phone", tel);
                paramMap.put("password", MD5.md5(pwd));
                LogUtils.log("MD5 STRING "+MD5.createSignString(paramMap) + HttpConstans.KEY);
                paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));

                HttpUtil.getInstance(this).postAsynHttp(HttpConstans.BASEURL+HttpConstans.LOGIN,paramMap,this,this, HttpAction.LOGIN);
                break;
            case R.id.login_zhiwen:
                if("".equals(SharePreferenceUtil.getData(this,SharePreferenceUtil.TOKENFILE,SharePreferenceUtil.REGIST_LOGINTOKEN))){
                    Utils.goNextActivity(this,SettingZwLoginActivity.class);
                }else{
                    Utils.goNextActivity(this,ZhiwenLoginActivity.class);
                }

                break;
            case R.id.tv_getyanzhnengma:
                if (pwdflag) {
                    //显示密码
                    login_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pwdflag = false;
                    tv_getyanzhnengma.setBackgroundResource(R.mipmap.regist_open);
                } else {
                    //否则隐藏密码
                    login_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pwdflag = true;
                    tv_getyanzhnengma.setBackgroundResource(R.mipmap.regist_close);
                }
                break;
            case R.id.rl_wx:
                login(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.rl_wb:
                login(SHARE_MEDIA.SINA);
                break;
            case R.id.rl_qq:
                login(SHARE_MEDIA.QQ);
                break;
        }
    }

    private int type;
    private void login(SHARE_MEDIA paramSHARE_MEDIA) {

        LogUtils.log("isAuthorize   " + UMShareAPI.get(this).isAuthorize(this, paramSHARE_MEDIA));
        if (UMShareAPI.get(this).isAuthorize(this, paramSHARE_MEDIA)) {
            this.type = 3;
            mShareAPI.deleteOauth(this, paramSHARE_MEDIA, this.listener);
        }else{
            this.type = 2;
            mShareAPI.doOauthVerify(this, paramSHARE_MEDIA, this.listener);
        }

    }


    private String uid;
    private String name;
    private String img;



    UMAuthListener listener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            LogUtils.log("Authorize succeed");
            if (type == 1) {
                LogUtils.log("doOauthVerify onComplete");
                uid = data.get("uid");
                name = data.get("name");
                img = data.get("iconurl");
                LogUtils.log("uid  " + PwdLoginActivity.this.uid);
                LogUtils.log("name  " + PwdLoginActivity.this.name);
                LogUtils.log("img  " + PwdLoginActivity.this.img);
                requestAdd();
            }else if(type == 2){//获取用户信息
                type = 1;
                PwdLoginActivity.this.mShareAPI.getPlatformInfo(PwdLoginActivity.this, platform, this);
            }else if(type == 3){//注销

                LogUtils.log("deleteOauth  onComplete");
                PwdLoginActivity.this.login(platform);
            }

        }


        private void requestAdd() {
            paramMap = new HashMap();
            paramMap.put("app_id", HttpConstans.appid);
            paramMap.put("channel_number", HttpConstans.qdnumber);
            paramMap.put("openid", uid);
            paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));
            HttpUtil.getInstance(PwdLoginActivity.this).postAsynHttp(HttpConstans.BASEURL+HttpConstans.SDK_LOGIN,paramMap,PwdLoginActivity.this,callBack, HttpAction.SDK_LOGIN);
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
        }
    };


    protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {
        super.onActivityResult(paramInt1, paramInt2, paramIntent);
        UMShareAPI.get(this).onActivityResult(paramInt1, paramInt2, paramIntent);
        this.mShareAPI.onActivityResult(paramInt1, paramInt2, paramIntent);
    }

}
